package com.hwhhhh.graduationproject.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hwhhhh.graduationproject.domain.model.User;
import com.hwhhhh.graduationproject.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 设置拦截器拦截请求
 * Created by Hwhhhh on 2021/3/3 21:22
 */

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> result = new HashMap<>();
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        try {
            // 验证token
            DecodedJWT decodedJWT = JWTUtils.verifyToken(token);
            // 获取token中的用户信息
            User user = new User();
            user.setId(Integer.parseInt(decodedJWT.getClaim("id").asString()));
            user.setIsAd(Integer.parseInt(decodedJWT.getClaim("isAd").asString()));
            // 放入request中
            request.setAttribute("currentUser", user);
            // 放行请求
            return true;
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            result.put("msg", "token已过期！");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            result.put("msg", "token算法不一致！");
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            result.put("msg", "无效签名！");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "token无效！");
        }
        result.put("code", 403);    // 设置状态码
        // 将map转为json，放入response中返回给前端
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }


}
